<template>
  <div
    class="w-full min-h-screen py-8 px-4 sm:px-6 lg:px-8"
  >
    <div class="max-w-6xl mx-auto">
      <div class="bg-white shadow-lg rounded-lg overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
          <h1 class="text-2xl font-bold text-gray-900">博客访客记录</h1>
          <p class="text-sm text-gray-600 mt-1">记录网站访问者的详细信息</p>
        </div>

        <!-- 访客列表 -->
        <div class="divide-y divide-gray-200">
          <div
            v-for="visitor in visitors"
            :key="visitor._id"
            class="px-6 py-4 hover:bg-gray-50 transition-colors duration-150"
          >
            <div class="flex items-center justify-between">
              <div class="flex-1">
                <div class="flex items-center space-x-4">
                  <div class="flex-shrink-0">
                    <div
                      class="w-10 h-10 bg-blue-500 rounded-full flex items-center justify-center"
                    >
                      <svg
                        class="w-5 h-5 text-white"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                        ></path>
                      </svg>
                    </div>
                  </div>
                  <div>
                    <div class="text-sm font-medium text-gray-900">
                      {{ visitor.ip }}  
                       <span class="text-xs text-gray-400"> 浏览：{{ visitor.adInfoOb.totNum }} 次</span>
                    </div>
                    <div class="text-sm text-gray-500">
                      来自：
                      {{ visitor.adInfoOb.province }} 
                      {{ visitor.adInfoOb.city }} 
                      {{ visitor.adInfoOb.district }}
                     
                    </div>
                    <div class="text-xs text-gray-400 mt-1">
                      {{ formatTime(visitor.adInfoOb.lastTime) }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="flex items-center space-x-2">
                <span
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                  :class="getCountryColor(visitor.adInfoOb.nation)"
                >
                  {{ visitor.adInfoOb.nation }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div v-if="hasMore" class="px-6 py-4 border-t border-gray-200">
          <div ref="loadMoreTrigger" class="text-center py-4">
            <div v-if="loading" class="flex justify-center items-center">
              <div
                class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"
              ></div>
              <span class="ml-2 text-gray-600">加载中...</span>
            </div>
            <!-- <button
              v-else
              @click="loadMore"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors duration-150"
            >
              加载更多
            </button> -->
          </div>
        </div>

        <!-- 空状态 -->
        <div
          v-if="visitors.length === 0 && !loading"
          class="px-6 py-12 text-center"
        >
          <svg
            class="mx-auto h-12 w-12 text-gray-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"
            ></path>
          </svg>
          <h3 class="mt-2 text-sm font-medium text-gray-900">暂无访客记录</h3>
          <p class="mt-1 text-sm text-gray-500">目前还没有访客访问记录</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";

interface Visitor {
  _id: string;
  ip: string;
  adInfoOb: {
    nation: string;
    district: string;
    city: string;
    province: string;
    lastTime: string;
    totNum:string
  };
}

const visitors = ref<Visitor[]>([]);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = ref(10);
const loadMoreTrigger = ref<HTMLElement>();

// 获取访客列表
const fetchVisitors = async (pageNum: number = 1, append: boolean = false) => {
  loading.value = true;
  try {
    const { data } = await $fetch(
      `/newapi/visitor/list?page=${pageNum}&pageSize=${pageSize.value}`,
      {
        method: "GET",
      }
    );
    if (data.total) {
      const { list, total } = data as {
        list: Visitor[];
        total: number;
      };
      if (append) {
        visitors.value.push(...list);
      } else {
        visitors.value = list;
      }

      hasMore.value = visitors.value.length < total;
    }
  } catch (error) {
    console.error("获取访客记录失败:", error);
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = async () => {
  if (!hasMore.value || loading.value) return;
  page.value++;
  await fetchVisitors(page.value, true);
};

// 格式化时间
const formatTime = (dateString: string) => {
  const date = new Date(+dateString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  // 转换为分钟
  const minutes = Math.floor(diff / 60000);
  if (minutes < 1) return "刚刚";
  if (minutes < 60) return `${minutes}分钟前`;
  if (minutes < 1440) return `${Math.floor(minutes / 60)}小时前`;
  if (minutes < 10080) return `${Math.floor(minutes / 1440)}天前`;
  return date.toLocaleDateString("zh-CN");
};

// 根据国家返回对应的颜色
const getCountryColor = (country: string) => {
  const colors = [
    "bg-red-100 text-red-800",
    "bg-yellow-100 text-yellow-800",
    "bg-green-100 text-green-800",
    "bg-blue-100 text-blue-800",
    "bg-indigo-100 text-indigo-800",
    "bg-purple-100 text-purple-800",
    "bg-pink-100 text-pink-800",
  ];

  let hash = 0;
  for (let i = 0; i < country.length; i++) {
    hash = country.charCodeAt(i) + ((hash << 5) - hash);
  }

  return colors[Math.abs(hash) % colors.length];
};

// 无限滚动
const observer = ref<IntersectionObserver>();

onMounted(async () => {
  await fetchVisitors();
  // 设置无限滚动
  if (loadMoreTrigger.value) {
    observer.value = new IntersectionObserver(
      async (entries) => {
        if (entries[0].isIntersecting && hasMore.value && !loading.value) {
          await loadMore();
        }
      },
      {
        rootMargin: "100px",
      }
    );
    observer.value.observe(loadMoreTrigger.value);
  }
});

onUnmounted(() => {
  if (observer.value) {
    observer.value.disconnect();
  }
});

// SEO
useHead({
  title: "访客记录 - 网站访问统计",
  meta: [
    {
      name: "description",
      content: "查看网站访客记录，包括访问者的IP地址、国家和城市信息",
    },
  ],
});
</script>

<style scoped>
/* 添加一些动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
